package eScrum.services.Impl;

import java.util.List;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;



import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.transaction.annotation.Transactional;

import eScrum.dao.UserDao;
import eScrum.entities.User;
import eScrum.entities.UserRole;
import eScrum.utils.EncryptionUtil;


public class ApplicationContextListener implements ApplicationListener<ApplicationEvent>{
	
	private UserDao userDao;
	private User adminUser = new User();
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Transactional
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ContextRefreshedEvent) {
			try {
			//	LOGGER.info("Application context refreshed or initialized.");
				List<User> users = userDao.findAll();
				if (users == null || users.size() == 0) {
				//	LOGGER.info("Database default values is being configured.");
					addAdminUser();
				}

			} catch (Exception e) {
				e.printStackTrace();
			//	LOGGER.info("Failed to add database default values.");
			}
		}		
	}
		private void addAdminUser() {
		//	LOGGER.info("Start to add admin user");
			try {

				adminUser.setFirstName("Admin");
				adminUser.setLastName("Admin");
				adminUser.setUsername("admin");
				adminUser.setPassword(EncryptionUtil.crypt("admin"));
				adminUser.setRole(UserRole.ADMIN);
				userDao.saveOrUpdate(adminUser);
		//		LOGGER.info("Admin user added");
			} catch (Exception e) {
				e.printStackTrace();
		//		LOGGER.info("Failed to add admin user");
			}
		}

}
